﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using HtmlAgilityPack;

namespace 合并页面
{
    /// <summary>
    /// 对于HTML，HTM文件的处理。
    /// </summary>
    public class HtmFile
    {
        string m_fullPath;   //全路径
        string m_fileName;   //文件名。
        string m_fileContent; //HTML文件BODY之间的内容。

        public string FullPath
        {
            get { return this.m_fullPath; }
        }

        public string FileName
        {
            get { return this.m_fileName; }
        }

        public string FileContent
        {
            get
            {
                StreamReader sr = new StreamReader(m_fullPath);
                string str = sr.ReadToEnd();
                sr.Close();
                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                htmlDoc.LoadHtml(str);
                HtmlAgilityPack.HtmlNode htmlNode = htmlDoc.DocumentNode;
                this.m_fileContent = htmlNode.SelectNodes("//body")[0].InnerHtml;
                return m_fileContent;
            }
        }

        public HtmFile()
        {

        }

        public HtmFile(string fullPath)
        {
            this.m_fullPath = fullPath;

            string[] temp = fullPath.Split('\\');
            this.m_fileName = temp[temp.Length - 1];

            StreamReader sr = new StreamReader(fullPath);
            string str = sr.ReadToEnd();
            sr.Close();
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(str);
            HtmlAgilityPack.HtmlNode htmlNode = htmlDoc.DocumentNode;
            this.m_fileContent = htmlNode.SelectNodes("//body")[0].InnerHtml;
        }

        /// <summary>
        /// 合并HTML文件。
        /// </summary>
        /// <param name="files"></param>
        public static string HeBingFile(MyArrayList htmFileList)
        {
            string content = "";
            StreamReader srHead = new StreamReader(System.Windows.Forms.Application.StartupPath + "\\head.dat", System.Text.Encoding.Default);
            string head = srHead.ReadToEnd();
            srHead.Close();
            StreamReader srFoot = new StreamReader(System.Windows.Forms.Application.StartupPath + "\\foot.dat", System.Text.Encoding.Default);
            string foot = srFoot.ReadToEnd();
            srFoot.Close();

            for (int i = 0; i < htmFileList.Count; i++)
            {
                content += ((HtmFile)htmFileList[i]).FileContent;
            }
            return head + content + foot;
        }

        /// <summary>
        /// 将HTM串写入到相应文件夹的文件中.
        /// </summary>
        /// <param name="htm">写入的内容</param>
        /// <param name="fileName">文件名</param>
        /// <param name="dirName">所属的文件夹</param>
        /// <returns></returns>
        public static void WriteHtmToFile(string htm, string fileName, string dirName)
        {
            string path = dirName + "\\" + fileName;
            if (!File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine(htm);
                }
            }
        }
        /// <summary>
        /// 读取一个HTML文档到
        /// </summary>
        /// <param name="htmlPageName"></param>
        /// <returns></returns>
        public static HtmlDocument ReadHTML(string htmlPageName)
        {
            StreamReader sr = new StreamReader(htmlPageName);
            string str = sr.ReadToEnd();
            sr.Close();
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(str);
            return htmlDoc;
        }

        /// <summary>
        /// 根据传入的编码得到相应的模板名称 如209 模特展示
        /// </summary>
        /// <param name="num">如209 210 211</param>
        /// <returns></returns>
        public static string GetHtmlTemplateName(int num)
        {
            string str = "";
            switch (num)
            {
                case 201: str = "促销海报"; break;
                case 202: str = "收藏我们"; break;
                case 203: str = "当季新品"; break;
                case 204: str = "温馨提示"; break;
                case 205: str = "形象展示"; break;
                case 206: str = "产品信息"; break;
                case 207: str = "产品尺码"; break;
                case 208: str = "搭配推荐"; break;
                case 209: str = "模特展示"; break;
                case 210: str = "颜色展示"; break;
                case 211: str = "产品细节"; break;
                case 212: str = "选款师介绍"; break;
                case 213: str = "选款师推荐"; break;
                case 214: str = "人气爆款"; break;
                case 215: str = "品质保证"; break;
                case 216: str = "尾部提示"; break;
            }
            return str;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="template">模板文件的路径 模板 205 206 207 209 210 211</param>
        /// <param name="linkTypeName">保存链接的类型Local,taogonghuo,lhl62411570,木子李ivy</param>
        /// <param name="fileCatName">文件的分类名称如1237-001 在TextBox中得到</param>
        /// <param name="type">图片的小分类A,B,C,D,E,F  在CombBox中得到</param>
        /// <param name="list">图片LIST</param>
        /// <returns></returns>
        public static HtmlDocument WriteHTML(string template, string linkTypeName,string fileCatName,string type,MyArrayList list)
        {
            HtmlDocument doc = ReadHTML(template);
            HtmlNodeCollection divImg = doc.DocumentNode.SelectNodes("//div/div");
            int divImgCount = divImg.Count;  //得到包含IMG的DIV节点个数.
            int listCount = list.Count;       //含有的图片个数
            ImageFile.ImgRename(list, template.Split('\\', '=')[1], type); //将List中图片进行重命名
            if (divImgCount > listCount)  //DIV->IMG节点的个数大于list中的图片数。删除文档中的节点
            {
                //删除的次数为两者的差值.
                for (int i = 0; i < divImgCount - listCount; i++)
                {
                    //从最后一个节点的前一个开始删除;如有10个节点,从第九个开始删除,其索引为8;
                    int delIndex = doc.DocumentNode.SelectNodes("//div/div").Count - 2;
                    doc.DocumentNode.SelectNodes("//div/div")[delIndex].Remove();
                }//删除节点后DIV-->IMG和List两者对齐.对齐后再开始更新链接.
            }
            else //小于时则要加入节点。
            {
                for (int i = 0; i < listCount - divImgCount; i++)
                {
                    HtmlNode newNode = HtmlNode.CreateNode("<DIV align='center' style='margin-top:5px'><IMG src='../images/209A10.jpg' style='min-width:700px; max-width:700px' /></DIV>" + "\r\n");
                    doc.DocumentNode.SelectSingleNode("//div").InsertBefore(newNode, divImg[divImgCount - 1]);
                }
            }
            //得到对齐后的DIV标签集合.
            HtmlNodeCollection divHNC = doc.DocumentNode.SelectNodes("//div/div");
            if (linkTypeName == "Local")
            {
                for (int i = 0; i < divHNC.Count; i++)
                {
                    ImageFile img = (ImageFile)list[i];
                    HtmlNode imgNode = divHNC[i].SelectSingleNode("img"); //得到DIV中的IMG标签节点
                    imgNode.Attributes["src"].Value = "../images/" + img.RenameImg;
                    if (img.MyImage.Width >= 550)
                    {
                        imgNode.Attributes["style"].Value = "min-width:700px; max-width:700px";
                    }
                    else
                    {
                        imgNode.Attributes["style"].Value = "min-width:550px; max-width:550px";
                    }
                }
            }
            else if (linkTypeName == "taogonghuo")
            {
               // com.taogonghuo.www.TaoGonghuo tgh = new 合并页面.com.taogonghuo.www.TaoGonghuo();
                object tgh = new object();
                //if (!tgh.DirExist(fileCatName))
                //    tgh.CreateDir(fileCatName);
                for (int i = 0; i < divHNC.Count; i++)
                {
                    ImageFile img = (ImageFile)list[i];
                    HtmlNode imgNode = divHNC[i].SelectSingleNode("img"); //得到DIV中的IMG标签节点
                    //tgh.UploadImage(ImageFile.GetImageByte(img.FullPath), fileCatName, img.RenameImg);
                    imgNode.Attributes["src"].Value = "http://www.taogonghuo.com/taobao/" + fileCatName + "/" + img.RenameImg;
                    if (img.MyImage.Width >= 550)
                    {
                        imgNode.Attributes["style"].Value = "min-width:700px; max-width:700px";
                    }
                    else
                    {
                        imgNode.Attributes["style"].Value = "min-width:550px; max-width:550px";
                    }
                }
            }
            else if (linkTypeName == "lhl62411570")
            {
                TaoBaoApi tb = new TaoBaoApi("lhl62411570");
                if (!tb.CatFileExist(fileCatName))
                    tb.CreateCatFile(fileCatName);
                for (int i = 0; i < divHNC.Count; i++)
                {
                    ImageFile img = (ImageFile)list[i];
                    HtmlNode imgNode = divHNC[i].SelectSingleNode("img"); //得到DIV中的IMG标签节点
                    string imgURL = tb.GetImageLink(fileCatName, img.RenameImg);
                    if (imgURL == "")
                        tb.UploadImage(fileCatName, img.RenameImg, img.FullPath);
                    else
                        tb.ReplaceImage(fileCatName, img.RenameImg, img.FullPath);
                    imgURL = tb.GetImageLink(fileCatName, img.RenameImg);
                    imgNode.Attributes["src"].Value = imgURL;
                    if (img.MyImage.Width >= 550)
                    {
                        imgNode.Attributes["style"].Value = "min-width:700px; max-width:700px";
                    }
                    else
                    {
                        imgNode.Attributes["style"].Value = "min-width:550px; max-width:550px";
                    }
                }
            }
            else   //木子李ivy
            {
                TaoBaoApi tb = new TaoBaoApi("木子李ivy");
                if (!tb.CatFileExist(fileCatName))
                    tb.CreateCatFile(fileCatName);
                for (int i = 0; i < divHNC.Count; i++)
                {
                    ImageFile img = (ImageFile)list[i];
                    HtmlNode imgNode = divHNC[i].SelectSingleNode("img"); //得到DIV中的IMG标签节点
                    string imgURL = tb.GetImageLink(fileCatName, img.RenameImg);
                    if (imgURL == "")
                        tb.UploadImage(fileCatName, img.RenameImg, img.FullPath);
                    else
                        tb.ReplaceImage(fileCatName, img.RenameImg, img.FullPath);
                    imgURL = tb.GetImageLink(fileCatName, img.RenameImg);
                    imgNode.Attributes["src"].Value = imgURL;
                    if (img.MyImage.Width >= 550)
                    {
                        imgNode.Attributes["style"].Value = "min-width:700px; max-width:700px";
                    }
                    else
                    {
                        imgNode.Attributes["style"].Value = "min-width:550px; max-width:550px";
                    }
                }
            }
            return doc;
        }
    }
}
